<template>
  <div class="login">
    <h3>授权加载中...</h3>
  </div>
</template>

<script>
import request from "@/utils/request";
import _ from "lodash";
import qs from "qs";
import { setToken, setCsrfToken } from "@/utils/auth";

export default {
  name: "Login",
  data() {
    return {
      loading: false,
      rsaPublic: "",
    };
  },
  created() {
    let queryString = qs.parse(window.location.search, {
      ignoreQueryPrefix: true,
    });
    if (queryString.code) {
      this.oauthLogin(queryString.code);
    } else {
      this.processOauth();
    }
  },
  methods: {
    getCsrfToken() {
      return new Promise((rs) => {
        request({
          url: "/getCsrfToken",
          method: "post",
        }).then((r) => {
          rs(r.token);
        });
      });
    },
    oauthLogin(code) {
      let params = {
        client_id: process.env.VUE_APP_SSO_CLIENT_ID || "qm-ui",
        client_secret: process.env.VUE_APP_SSO_CLIENT_SECRET || "secret-qm-ui",
        grant_type: "authorization_code",
        code: code,
        redirect_uri: process.env.VUE_APP_SSO_REDIRECT_URL,
      };
      request({
        url: "/oauth/token",
        method: "post",
        data: params,
      }).then((r) => {
        // r.access_token 是使用了 r.jti 加密的带有认证信息的字符串，r.jti 则是 App 框架最初生成的 token，也是 TokenAuthenticationFilter.java 可以直接校验的 token
        // setToken(r.access_token);
        setToken(r.jti);
        // 前后端分离没必要启用 csrf
        this.getCsrfToken().then((csrfToken) => {
          setCsrfToken(csrfToken);
        });

        let uri = localStorage.getItem("sso_redirect_uri") || "/";
        localStorage.removeItem("sso_redirect_uri");
        this.$router.push(uri);
      });
    },
    processOauth() {
      let params = {
        client_id: process.env.VUE_APP_SSO_CLIENT_ID || "qm-ui",
        redirect_uri: process.env.VUE_APP_SSO_REDIRECT_URL,
        response_type: "code",
        state: process.env.VUE_APP_SSO_CLIENT_ID || "qm-ui",
      };
      window.location.href = `${process.env.VUE_APP_SERVER}/oauth/authorize?client_id=${params.client_id}&redirect_uri=${params.redirect_uri}&response_type=code&state=qm-ui`;
      // request({
      //   url: "/oauth/authorize",
      //   params: params,
      //   headers: { "qm-ui": true },
      // }).then((r) => {
      //   if (r && r.sso) {
      //     window.location.href = `${process.env.VUE_APP_SERVER}/sso/oauth/login`;
      //   } else {
      //     this.notifyError("获取数据失败");
      //   }
      // });
    },
  },
};
</script>

<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  text-align: center;
}
</style>
